<?php
/**
* @package mosRest
* @author Chad Auld and Ozgur Cem Sen (code@brilaps.com)
* @copyright Brilaps, LLC (http://brilaps.com)
* @link http://brilaps.com || http://wiki.brilaps.com
* @license http://www.opensource.org/licenses/gpl-license.php GNU/GPL v.2.
*/

/**
* A statistics class that builds on the com_rest base REST component.  This class aims to RESTify MiaCMS's
* stat data so that it can be consumed by external interface (ex) charting apps, monitoring tools, etc.
* 
* Note: Remember most of these stats are only collected if MiaCMS's global stat trackers have been enabled
*/
class mRestStats extends mRest {
	
	/**
	* Retrieves agent stat data from the mos_stats_agents table.  Information such as which browsers, operating
	* systems, etc are connecting to the site.
	* @param returnFormat - return format requested (ex) json, xml, php
	* @param callback - the requested JSON callback function name
	*/
	function getAgentStats($returnFormat, $callback) {
		global $database;
		
    	$query = "SELECT agent, type,"
                . "\n CASE"
                . "\n WHEN m.type=0 THEN 'Browser'"
                . "\n WHEN m.type=1 THEN 'OS'"
                . "\n WHEN m.type=2 THEN 'Host'"
                . "\n ELSE 'Other'"
                . "\n END as type_desc, "
                . "\n hits"
                . "\n FROM #__stats_agents m";
		
		$database->setQuery($query);
		$dbResults = $database->loadObjectList();
		
		if ($returnFormat=='json' || $returnFormat=='php') {
		    $data = $this->encodeRestResponse($dbResults, $returnFormat, $callback);
		} else if ($returnFormat=='xml') {
		    //For XML we must build the full XML doc
			$dom = new DOMDocument("1.0");
			//Create the root element
			$root = $dom->createElement("ResultSet");
			$dom->appendChild($root);

			if (empty($dbResults)) {
				//No result so just add a single empty node
				$message = $dom->createElement("Result");
				$root->appendChild($message);
			} else {
				//We have results so process accordingly
				foreach($dbResults as $dbResult) {
					//Create child elements
					$content = $dom->createElement("Result");
					$root->appendChild($content);
					//Add the agent element
					$agent = $dom->createElement("agent");
					$content->appendChild($agent);
					$agent->appendChild($dom->createTextNode($dbResult->agent));
					//Add type element
					$type = $dom->createElement("type");
					$content->appendChild($type);
					$type->appendChild($dom->createTextNode($dbResult->type));
					//Add type_desc element
					$type_desc = $dom->createElement("type_desc");
					$content->appendChild($type_desc);
					$type_desc->appendChild($dom->createTextNode($dbResult->type_desc));
					//Add hits element
					$hits = $dom->createElement("hits");
					$content->appendChild($hits);
					$hits->appendChild($dom->createTextNode($dbResult->hits));
				}
			}
			//Save xml tree
			$data = $dom->saveXML();
		}

		return $data;	
	}
	
	/**
	* Retrieves collected end user search terms and the number of times they have been searched for
	* @param returnFormat - return format requested (ex) json, xml, php
	* @param limit - used to limit the number of records returned (ex) grab top 5 most popular search terms
	* @param callback - the requested JSON callback function name
	*/
    function getSearchStats($returnFormat, $limit, $callback) {
		global $database;
		
		//Setup query
    	$query = "SELECT search_term, hits"
                . "\n FROM #__core_log_searches"
                . "\n ORDER BY hits DESC";
		
		if ($limit>0) {
		    //Setup query
    		$query .= "\n LIMIT {$limit}";
		}
		
		$database->setQuery($query);
		$dbResults = $database->loadObjectList();
		
		if ($returnFormat=='json' || $returnFormat=='php') {
		    $data = $this->encodeRestResponse($dbResults, $returnFormat, $callback);
		} else if ($returnFormat=='xml') {
		    //For XML we must build the full XML doc
			$dom = new DOMDocument("1.0");
			//Create the root element
			$root = $dom->createElement("ResultSet");
			$dom->appendChild($root);

			if (empty($dbResults)) {
				//No result so just add a single empty node
				$message = $dom->createElement("Result");
				$root->appendChild($message);
			} else {
				//We have results so process accordingly
				foreach($dbResults as $dbResult) {
					//Create child elements
					$content = $dom->createElement("Result");
					$root->appendChild($content);
					//Add search_term element
					$search_term = $dom->createElement("search_term");
					$content->appendChild($search_term);
					$search_term->appendChild($dom->createTextNode($dbResult->search_term));
					//Add hits element
					$hits = $dom->createElement("hits");
					$content->appendChild($hits);
					$hits->appendChild($dom->createTextNode($dbResult->hits));
				}
			}
			//Save xml tree
			$data = $dom->saveXML();
		}
		
		return $data;	
	}
	
	/**
	* Retrieves a list of content items contained in the site with number of times they have been viewed
	* @param returnFormat - return format requested (ex) json, xml, php
	* @param limit - used to limit the number of records returned (ex) grab top 5 most viewed content items
	* @param callback - the requested JSON callback function name
	*/
	function getContentStats($returnFormat, $limit, $callback) {
		global $database;
		
		//Setup query
    	$query = "SELECT id, title , hits"
                . "\n FROM #__content"
                . "\n ORDER BY hits DESC";
		
		if ($limit>0) {
		    //Setup query
    		$query .= "\n LIMIT {$limit}";
		}
		
		$database->setQuery($query);
		$dbResults = $database->loadObjectList();
		
		if ($returnFormat=='json' || $returnFormat=='php') {
		    $data = $this->encodeRestResponse($dbResults, $returnFormat, $callback);
		} else if ($returnFormat=='xml') {
		    //For XML we must build the full XML doc
			$dom = new DOMDocument("1.0");
			//Create the root element
			$root = $dom->createElement("ResultSet");
			$dom->appendChild($root);
			
			if (empty($dbResults)) {
				//No result so just add a single empty node
				$message = $dom->createElement("Result");
				$root->appendChild($message);
			} else {
				//We have results so process accordingly
				foreach($dbResults as $dbResult) {
					//Create child elements
					$content = $dom->createElement("Result");
					$root->appendChild($content);
					//Add the id element
					$id = $dom->createElement("id");
					$content->appendChild($id);
					$id->appendChild($dom->createTextNode($dbResult->id));
					//Add title element
					$title = $dom->createElement("title");
					$content->appendChild($title);
					$title->appendChild($dom->createCDATASection($dbResult->title));
					//Add hits element
					$hits = $dom->createElement("hits");
					$content->appendChild($hits);
					$hits->appendChild($dom->createTextNode($dbResult->hits));
				}
			}
			//Save xml tree
			$data = $dom->saveXML();
		}
		
		return $data;	
	}
	
	/**
	* Retrieves a count of guest and regisitered users currently browsing the site
	* Note: mirrors mod_whosonline
	*
	* @param returnFormat - return format requested (ex) json, xml, php
	* @param callback - the requested JSON callback function name
	*/
	function getWhosOnline($returnFormat, $callback) {
		global $database;
		
		//Setup guest query
    	$guestQuery = "SELECT count(session_id) as guests_online FROM #__session WHERE guest=1 AND (usertype is NULL OR usertype='')";
    	$database->setQuery($guestQuery);
		$guestResults = $database->loadObjectList();
		$guest_count = $guestResults[0]->guests_online;
		
		//Setup user query
    	$reguserQuery = "SELECT DISTINCT count(username) as users_online" 
    	            . "\n FROM #__session WHERE guest=0 AND usertype <> 'administrator' AND usertype <> 'superadministrator'";
    	$database->setQuery($reguserQuery);
		$reguserResults = $database->loadObjectList();
		$reguser_count = $reguserResults[0]->users_online;
		
		$whosonline = array('guests'=>$guest_count, 'registered_users'=>$reguser_count, 
		                    'total'=>($guest_count + $reguser_count));
		 
		if ($returnFormat=='json' || $returnFormat=='php') {
		    $data = $this->encodeRestResponse($whosonline, $returnFormat, $callback);
		} else if ($returnFormat=='xml') {
		    //For XML we must build the full XML doc
			$dom = new DOMDocument("1.0");
			//Create the root element
			$root = $dom->createElement("ResultSet");
			$dom->appendChild($root);
			
			if (empty($guestResults) && empty($reguserResults)) {
				//No result so just add a single empty node
				$message = $dom->createElement("Result");
				$root->appendChild($message);
			} else {
				//We have results so process accordingly
				//Create child elements
				$content = $dom->createElement("Result");
				$root->appendChild($content);
				//Add the guest element
				$guests = $dom->createElement("guests");
				$content->appendChild($guests);
				$guests->appendChild($dom->createTextNode($guest_count));
				//Add the registered user element
				$registered_users = $dom->createElement("registered_users");
				$content->appendChild($registered_users);
				$registered_users->appendChild($dom->createTextNode($reguser_count));
				//Sum for the total
				$total = $dom->createElement("total");
				$content->appendChild($total);
				$total->appendChild($dom->createTextNode($guest_count + $reguser_count));
			}
			//Save xml tree
			$data = $dom->saveXML();
		} 
		
		return $data;	
	}
	
}

?>